
import dayjs from "dayjs"
import { getFormList } from "@/api"
import { dateTimeKV } from "@/utils"
export default {
	data(){
		return {
			// commonFormFuntype: "", // 引用的页面需要显式定义
			// 通用表单
			commonForm: {
				loading: false,
				finished: false,
				columns: [],
				tableData: [],
				formConf: [],
				param: {
					page: 1,
					limit: 20
				},
				searchValue: {},
				countList: [],
				sonData: {},
				// 初次赋值 searchValue， sonData不触发
				reqCount: 0,
				timeConf: {}
			}
		}
	},
	watch: {
		"commonForm.searchValue": {
			handler(n){
				if(this.commonForm.reqCount > 1) return this.formInit()
			},
			deep: true
		},
		"commonForm.sonData": {
			handler(){
				if(this.commonForm.reqCount > 1) return this.formInit()
			},
			deep: true
		}
	},
	methods: {
		getCommonFormList(){
			const {
				loading,
				finished,
				columns,
				tableData,
				formConf,
				searchValue,
				countList,
				param,
				sonData,
				timeConf
			} = this.commonForm
			if(loading) return
			this.commonForm.loading = true
			let params = {
				...param,
				...this.formatTimeConf(searchValue, timeConf),
				...sonData
			}
			getFormList({
				funtype: this.commonFormFuntype,
				param: params
			}).then(res => {
				const { data, code } = res
				if(code === 1){
					if(!columns.length){
						this.commonForm.columns = data.fieldList
					}
					if(!formConf.length){
						this.commonForm.formConf = data.formFieldList
						// 处理时间回显配置
						this.commonForm.timeConf = dateTimeKV(data.formFieldList)
						this.commonForm.searchValue = this.formatTimeConf(this.matchSearchKey(data.formFieldList), this.commonForm.timeConf)
						this.commonForm.reqCount = 1
					}
					if(data.param.page === 1){
						this.commonForm.countList = data.countList.list || []
					}
					this.commonForm.param.page++
					this.commonForm.tableData = this.commonForm.tableData.concat(data.list.data)
					if(this.commonForm.tableData.length >= data.list.total){
					  this.commonForm.finished = true;
					}
					setTimeout(() => {
						this.commonForm.reqCount = 2
					}, 1000)
				}
			}).finally(() => {
				this.commonForm.loading = false
			})
		},
		formInit(fn){
			this.commonForm.tableData = []
			this.commonForm.finished = false
			this.commonForm.param.page = 1
			this.getCommonFormList()
			fn && fn()
		}
	}
}